package cn.lnexin.file;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileDirUtil {
	
	public static List<String> iterationScanFiles(String tarDir) {
		iterAllFileList.clear();
		getAllFileList(tarDir);
		return iterAllFileList;
	}
	
	/**
	 * @param dir
	 *            制定的总目录
	 * @param limittDirs
	 *            父目录过滤过滤,传入指定的过滤目录集合
	 * @return
	 */
	public static List<String> iterationScanFiles(String dir, List<String> limittDirs) {
		iterAllFileList.clear();
		getAllFileListLimitParent(dir);
		return iterAllFileList;
	}
	
	private static List<String> iterAllFileList = new ArrayList<>();
	
	// 对父母目录文件夹名字进行一次限制
	private static List<String> getNames() {
		List<String> names = new ArrayList<>();
		for (int i = 1001; i < 9000; i++) {
			names.add(String.valueOf(i));
		}
		return names;
	}
	
	// 对父目录做限制
	private static void getAllFileListLimitParent(String src_dir) {
		File file = new File(src_dir);
		List<String> names = getNames();
		if (!file.isFile() && file.isDirectory()) {
			File[] fileLists = file.listFiles();
			for (int i = 0; i < fileLists.length; i++) {
				File child = fileLists[i];
				if (child.isDirectory() && names.contains(child.getName())) {
					getAllFileList(fileLists[i].getPath());
				}
				if (fileLists[i].isFile() && names.contains(child.getParentFile().getName())) {
					iterAllFileList.add(fileLists[i].getPath());
					
				}
			}
		}
	}
	
	// 不对父目录做限制
	private static void getAllFileList(String src_dir) {
		File file = new File(src_dir);
		if (!file.isFile() && file.isDirectory()) {
			File[] fileLists = file.listFiles();
			for (int i = 0; i < fileLists.length; i++) {
				File child = fileLists[i];
				if (child.isDirectory()) {
					getAllFileList(fileLists[i].getPath());
				}
				if (fileLists[i].isFile()) {
					iterAllFileList.add(fileLists[i].getPath());
					
				}
			}
		}
	}
	
	// 获取一个目录下的所有文件,不迭代
	public static String[] childrenFiles(String src_dir, String filter_str) {
		ArrayList<String> list = new ArrayList<String>();
		File file = new File(src_dir);
		File[] files = file.listFiles();
		for (int i = 0; i < files.length; i++) {
			if (!files[i].isDirectory()) {
				if (files[i].getName().indexOf(filter_str) != -1) {
					list.add(files[i].getName());
				}
			}
		}
		if (list.size() > 0) {
			String[] re = new String[list.size()];
			for (int i = 0; i < list.size(); i += 1) {
				re[i] = list.get(i);
			}
			return re;
		} else {
			return null;
		}
	}
}
